package cc.javaee.bbs.task;

import cc.javaee.bbs.annotations.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

import java.util.Calendar;

/**
 * 定时任务模板类
 * @author xdw
 */
@PropertySource("classpath:/config.properties")
public abstract class AbstractJobTemplate {

    //开关
    @Value("${on_off.Job}")
    protected boolean onOffJob;

    Logger logger = LoggerFactory.getLogger(getClass());

    //是否运行
    private boolean isRunning = false;

    private ThreadLocal<Long> longThreadLocalTime = new ThreadLocal<>();
    private ThreadLocal<String> longThreadLocalMsg = new ThreadLocal<>();

    private void startLog(String msg) {
        logger.info(msg + "跑批开始");
        longThreadLocalMsg.set(msg);
        longThreadLocalTime.set(Calendar.getInstance().getTimeInMillis());
    }

    private void endLog() {
        String msg = longThreadLocalMsg.get();
        long startTime = longThreadLocalTime.get();
        Long endTime = Calendar.getInstance().getTimeInMillis();
        logger.info(msg + "跑批完成,共耗时:" + (endTime - startTime));

        longThreadLocalTime.remove();
        longThreadLocalMsg.remove();
    }

    protected abstract void execute();

    /**
     * 模板方法
     * @param msg
     */
    public void templateMethod(String msg) {
        if (!onOffJob) {
            return;
        }
        if (isRunning) {
            return;
        }
        startLog(msg);
        isRunning = true;

        try {
//            Task task = this.getClass().getMethod("execute").getAnnotation(Task.class);
            Task task = this.getClass().getDeclaredMethod("execute").getAnnotation(Task.class);
            if (task != null && task.dbLog()) {
                // TODO: 2018/3/3 保存记录到数据库
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        try {
            execute();
        } catch (Exception e) {
            logger.error("demo跑批失败！", e);
        } finally {
            isRunning = false;
        }

        endLog();

    }
}
